//
//  CSSiteNameVC.m
//  ProjectforHDX
//
//  Created by yinda on 2018/7/27.
//  Copyright © 2018年 H.DX. All rights reserved.
//

#import "CSSiteNameVC.h"
#import "SearchBar.h"
#import "CSSiteNameCell.h"
#import "CSSiteNameModel.h"

@interface CSSiteNameVC ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong)SearchBar *searchBar;

@property(nonatomic, strong)NSString *searchKey;

@property(nonatomic ,strong)NSMutableArray *faultedPlates;

@property(nonatomic, strong)NSMutableDictionary *params;

@end

@implementation CSSiteNameVC{
    UITextField *siteNameTextField;
    UITextField *siteIDTextField;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self horizontalscreensetting];
    self.labnav.text = @"选择站点";
    self.faultedPlates = [NSMutableArray new];
    [self requestData];
    [self setupView];
    // Do any additional setup after loading the view.
}

// 设置横屏
- (void)horizontalscreensetting{
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    //允许转成横屏
    appDelegate.shouldChangeOrientation = YES;
    NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
    [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
    NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    // 恢复成竖屏
    AppDelegate * app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    app.shouldChangeOrientation = NO;
    NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
    [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
    NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}

-(void)requestData
{
    [[BDHUD sharedManager] showBDHUD:self.view title:@"HUD.title"];
    sleep(0.5);
    [[BDHUD sharedManager] dismissHUD];
    
    _params = [NSMutableDictionary dictionary];
    // orderType
    NSString *sitename;
    NSString *siteID;
    if (siteNameTextField==nil||siteNameTextField.text==nil) {
        sitename = @"";
    }
    else{
        sitename = siteNameTextField.text;
    }
    if (siteIDTextField==nil||siteIDTextField.text==nil) {
        siteID = @"";
    }
    else{
        siteID = siteIDTextField.text;
    }
    if (!self.siteDic) {
        [self.params setObject:@"" forKey:@"userId"];
    }
    else{
       [self.params setObject:self.siteDic[@"faultid"] forKey:@"userId"];
    }
    [_params setObject:sitename forKey:@"siteNameEN"];
    [self.params setObject:siteID forKey:@"siteID"];
//    [_params setValue:self.orderType forKey:@"orderType"];
    
    NSLog(@"%@",_params);
    [[BDHUD sharedManager] showBDHUD:self.view title:nil];
    [AFHttpTool postJsonDatawithUrl:@"getSite"parameters:_params success:^(id responseObject) {
        [[BDHUD sharedManager] dismissHUD];
        if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
            NSArray *data=[responseObject objectForKey:@"data"];
            NSLog(@"%@",data);
            CSSiteNameModel *model = [[CSSiteNameModel alloc]init];
            for (NSDictionary *dic in data) {
                model.Id = [dic objectForKey:@"id"];
                model.custCode = [dic objectForKey:@"custCode"];
                model.custName = [dic objectForKey:@"custName"];
                model.siteId = [dic objectForKey:@"siteID"];
                model.siteNameCN = [dic objectForKey:@"siteNameCN"];
                model.siteNameEN = [dic objectForKey:@"siteNameEN"];
                [self.faultedPlates addObject:[THMangerTool deepCopy:model]];
            }
            [self.tableView reloadData];
            
        }
        else{
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
            else{
                [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
            }
            
        }
    } fail:^(id responseObject, NSError *error) {
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [siteNameTextField resignFirstResponder];
    [siteIDTextField resignFirstResponder];
}

//初始化view
-(void)setupView
{
    UITableView *table =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
    table.delegate = self;
    table.dataSource = self;
    [table setFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    self.tableView.backgroundColor = [UtilCheck hexStringToColor:@"F7F5FA" alpha:1.0];
    [self.view addSubview:table];
    self.tableView = table;
    
//    UISearchBar *search = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
//    search.backgroundColor =[UIColor whiteColor];
//    [search setImage:BDFILEIMAGENAEM(@"default/iconfont-sousuo") forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
//    search.placeholder = [UtilCheck language:@"customer.search"];
//    UITextField *searchField = [search valueForKey:@"_searchField"];
    
    // Change the search bar placeholder text color
//    [searchField setValue:[UtilCheck hexStringToColor:@"ababab" alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];
//    searchField.font = CustomFont(13);
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 51)];
    UILabel *sitenameLabel  =[[UILabel alloc]initWithFrame:CGRectMake(20, 15, 70, 21)];
    sitenameLabel.font = [UIFont systemFontOfSize:15];
    sitenameLabel.text = [NSString stringWithFormat:@"%@:",[UtilCheck language:@"order.station.name"]];
    [headView addSubview:sitenameLabel];
    
    siteNameTextField = [[UITextField alloc]initWithFrame:CGRectMake(95, 14, 150, 25)];
    siteNameTextField.borderStyle = UITextBorderStyleRoundedRect;
    siteNameTextField.font = [UIFont systemFontOfSize:13];
    [headView addSubview:siteNameTextField];
    
    UILabel *siteIDLabel  =[[UILabel alloc]initWithFrame:CGRectMake(260, 15, 60, 21)];
    siteIDLabel.text = [UtilCheck language:@"siteNameVC.SiteID"];
    siteIDLabel.font = [UIFont systemFontOfSize:15];
    [headView addSubview:siteIDLabel];
    
    siteIDTextField = [[UITextField alloc]initWithFrame:CGRectMake(325, 14, 150, 25)];
    siteIDTextField.borderStyle = UITextBorderStyleRoundedRect;
    siteIDTextField.font = [UIFont systemFontOfSize:13];
    [headView addSubview:siteIDTextField];
    
    UIButton *seachButton = [UIButton buttonWithType:0];
    seachButton.frame = CGRectMake(480, 10, 80, 30);
    [seachButton setTitle:[UtilCheck language:@"setting.query"] forState:0];
    seachButton.layer.cornerRadius = 5;
    seachButton.layer.masksToBounds = YES;
    [seachButton addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    seachButton.backgroundColor = SYSTEM_COLOR;
    [headView addSubview:seachButton];
    
    self.tableView.tableHeaderView = headView;
    
//    search.backgroundImage = [self imageWithColor:[UtilCheck hexStringToColor:@"#E8E8E8" alpha:1.0] size:search.bounds.size];
//
//    search.delegate = self;
    
}

- (void)searchAction:(UIButton *)button{
    //    if ([searchText isEqualToString:@""]) {
    //        [self.faultedPlates removeAllObjects];
    //        [self requestData];
    //
    //    }else {
    [siteIDTextField resignFirstResponder];
    [siteNameTextField resignFirstResponder];
    [self.faultedPlates removeAllObjects];
    [self requestData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//取消searchbar背景色
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

#pragma -mark tableview 的 delegate  datasource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    return 5;
    return self.faultedPlates.count+1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_tableView registerNib:[UINib nibWithNibName:@"CSSiteNameCell" bundle:nil] forCellReuseIdentifier:@"CSSiteNameCell"];
    CSSiteNameCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CSSiteNameCell" forIndexPath:indexPath];
    if (indexPath.row==0) {
        CSSiteNameModel *model = [[CSSiteNameModel alloc]init];
        model.siteNameCN = [UtilCheck language:@"siteNameVC.SiteNameCN"];
        model.siteNameEN = [UtilCheck language:@"siteNameVC.SiteNameEN"];
        model.siteId = [UtilCheck language:@"siteNameVC.SiteID"];
        model.custCode = [UtilCheck language:@"siteNameVC.CustomerCode"];
        model.custName = [UtilCheck language:@"siteNameVC.CusName"];
        cell.model = model;
    }
    else{
        cell.model = self.faultedPlates[indexPath.row-1];
        cell.siteName.font = [UIFont systemFontOfSize:13];
        cell.siteName.textAlignment = NSTextAlignmentLeft;
        cell.siteID.font = [UIFont systemFontOfSize:13];
        cell.CustomerName.font = [UIFont systemFontOfSize:13];
        cell.CustomerNumLabel.font = [UIFont systemFontOfSize:13];
        cell.sitechinaName.font = [UIFont systemFontOfSize:13];
        cell.sitechinaName.textAlignment = NSTextAlignmentLeft;
        
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row!=0) {
        CSSiteNameModel *model = self.faultedPlates[indexPath.row-1];
        NSMutableDictionary *dataDic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:model.Id,@"faultid",model.custName,@"custName",model.custCode,@"custCode",model.siteId,@"siteId" ,model.siteNameCN,@"siteNameCN",model.siteNameEN,@"siteNameEN",nil];
        NSLog(@"数据%@",dataDic);
        //创建一个消息对象
        NSNotification * notice = [NSNotification notificationWithName:@"stationName" object:nil userInfo:dataDic];
        //发送消息
        [[NSNotificationCenter defaultCenter]postNotification:notice];
        [[self navigationController] popViewControllerAnimated:YES];
    }

}
#pragma -mark searchbar  的 delegate
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
    NSMutableArray *ma = [[NSMutableArray alloc]init];
    for (NSDictionary *model in self.faultedPlates) {
        if ([model[@"name"] hasPrefix:[NSString stringWithFormat:@"%@",self.searchKey]]) {
            [ma addObject:model];
        }
    }
    self.faultedPlates = ma;
    [self.tableView reloadData];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"%@",searchBar);
    self.searchKey = searchBar.text;
    
    //    if ([searchText isEqualToString:@""]) {
    //        [self.faultedPlates removeAllObjects];
    //        [self requestData];
    //
    //    }else {
    [self.faultedPlates removeAllObjects];
    [self requestData];
    //    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45.f;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

@end
